﻿using Newtonsoft.Json;
using System.Text;

namespace Tester.Models;

public class ReadAndWrite
{
    /// <summary>
    /// 必须和Deserialize一起使用
    /// </summary>
    /// <returns></returns>
    private static async void ReadPermission()
    {
#if ANDROID
            PermissionStatus statusread = await Permissions.RequestAsync<Permissions.StorageRead>();
#endif
    }

    internal static string FileRead()
    {
#if ANDROID
    ReadPermission();
    string path = "/storage/emulated/0/Tester/test.json";
#elif WINDOWS
    string path = Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments) + "\\Tester\\test.json";
#else
    string path = string.Empty;
#endif
        if (File.Exists(path) == false)
        {
            return string.Empty;
        }
        FileStream fs = new(path, FileMode.Open);
        StreamReader sr = new(fs, Encoding.UTF8);
        string str = sr.ReadToEndAsync().Result;
        sr.Close();
        fs.Close();
        return str;
    }

    internal static Views.CommonConfig Deserialize(string str)
    {
        Views.CommonConfig config = new Views.CommonConfig();
        if (str == string.Empty)
        {
            return null;
        }
        config = JsonConvert.DeserializeObject<Views.CommonConfig>(str);
        return config;
    }

    internal static async void Write(object ObjectToWrite)
    {
#if ANDROID
        PermissionStatus statuswrite = await Permissions.RequestAsync<Permissions.StorageWrite>();
        string path = "/storage/emulated/0/Tester";
        if (Directory.Exists(path) == false)
        {
            Directory.CreateDirectory(path);
        }
        FileStream fs = new(path + "/test.json", FileMode.Create);
        StreamWriter sw = new StreamWriter(fs, Encoding.UTF8);
        string str = JsonConvert.SerializeObject(ObjectToWrite);
        await sw.WriteAsync(str);
        sw.Close();
        fs.Close();
#elif WINDOWS
        string path = Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments) + "\\Tester";
        if (Directory.Exists(path) == false)
        {
            Directory.CreateDirectory(path);
        }
        FileStream fs = new(path + "\\test.json", FileMode.Create);
        StreamWriter sw = new StreamWriter(fs, Encoding.UTF8);
        string str = JsonConvert.SerializeObject(ObjectToWrite);
        await sw.WriteAsync(str);
        sw.Close();
        fs.Close();
#endif
    }

   
}